import type { TreeDataType } from "../type";

export function findNode(
  key: string | number,
  data?: TreeDataType
): TreeDataType[0] | undefined {
  if (!data) return undefined;
  for (const i of data) {
    if (i.key == key) return i;
    const t = findNode(key, i.children);
    if (t) return t;
  }
}

export function findParentNode(
  key: string | number,
  data: TreeDataType,
  parentKey?: string | number
): string | number | undefined {
  for (const i of data) {
    if (i.key == key) return parentKey;
    if (i.children) {
      const p = findParentNode(key, i.children, i.key);
      if (p) return p;
    }
  }
}

export function cloneTreeData(
  treeData?: TreeDataType,
  excludeKey?: string | number
): TreeDataType | undefined {
  // 直接更新 treeData 的节点信息，React 无法识别，导致不更新数据，所以需要重新复制一遍
  const clonedData: TreeDataType = [];
  if (!treeData) return;
  for (const item of treeData) {
    if (excludeKey !== item.key) {
      clonedData.push({
        ...item,
        children: cloneTreeData(item.children, excludeKey),
      });
    }
  }
  if (clonedData.length == 0) return;
  return clonedData;
}
